import React, { useEffect, useState } from "react";
import { useParams, useNavigate } from "react-router-dom";
import { Swiper, Toast, Button } from "antd-mobile";
import axios from "axios";


import { HeartOutline } from 'antd-mobile-icons'
const FALLBACK_IMG = "https://via.placeholder.com/300x200?text=加载失败";

export default function Detail() {
  const { id } = useParams();
  
  const navigate = useNavigate();
  const [data, setData] = useState(null);
  const [searchText, setSearchText] = useState("");
  const [guessList, setGuessList] = useState([]);
  const [collect, setCollect] = useState('');
  useEffect(() => {
    const fetchDetail = async () => {
      try {
        const res = await axios.get(`http://127.0.0.1:3000/item/?id=${id}`);
        setData(res.data.info);
      } catch (err) {
        Toast.show({ icon: "fail", content: "加载失败" });
      }
    };
    fetchDetail();
  }, [id]);
   //猜你喜欢
  useEffect(() => {
    const fetchGuessList = async () => {
      if (!data) return;
      try {
        const res = await axios.get("http://127.0.0.1:3000/recommend", {
          params: {
            category: data.type,
            exclude: data._id,
          },
        });
        setGuessList(res.data.info || []);
      } catch (err) {
        console.error("猜你喜欢加载失败", err);
      }
    };
    fetchGuessList();
  }, [data]);

//收藏
  // 获取收藏状态函数
const getCollectStatus = async () => {
  try {
    const res = await axios.get("http://127.0.0.1:3000/collect-status", {
      params: { id },
    });

    if (res.data.code === 0) {
      // 设置本地状态（例如：setCollect(res.data.collect)）
      setCollect(res.data.collect);
    } else {
      Toast.show({ icon: "fail", content: res.data.msg || "获取收藏状态失败" });
    }
  } catch (err) {
    Toast.show({ icon: "fail", content: "请求失败" });
  }
};
useEffect(() => {
getCollectStatus();

},[])
  
const shoucang = async () => {
  
  try {
    const res = await axios.post("http://127.0.0.1:3000/collect", {
      id,
      isCollect:!collect,
    });

    if (res.data.code === 0) {
      Toast.show({
        icon: "success",
        content: res.data.msg || "操作成功",
        
      });
      getCollectStatus()

    } else {
      Toast.show({
        icon: "fail",
        content: res.data.msg || "收藏失败",
      });
    }
  } catch (err) {
    Toast.show({ icon: "fail", content: "请求失败" });
  }
};



  if (!data) {
    return <div style={{ padding: 20, textAlign: "center" }}>加载中...</div>;
  }
//  const handleSearch = () => {
//   navigate("/so", { state: { keyword: searchText } });
// };

  return (
    <div
      style={{
        background: "#f5f5f5",
        minHeight: "100vh",
        fontFamily: "system-ui",
      }}
    >
      {/* 返回按钮 */}
      <div
        style={{
          display: "flex",
          alignItems: "center",
          padding: "8px 12px",
          background: "#fff",
          borderBottom: "1px solid #eee",

        }}
      >
        <Button
          onClick={() => navigate('/shou')}
          size="small"
          style={{ marginRight: 8 }}
        >
          {" "}
          返回{" "}
        </Button>
        <input
          value={searchText}
          onChange={(e) => setSearchText(e.target.value)}
          placeholder="请输入关键词"
          onFocus={() => navigate("/so")}
          style={{
            flex: 1,
            borderRadius: 20,
            padding: "4px 12px",
            background: "#f5f5f5",
            border: "1px solid #ddd",
          }}
        />
        <Button
          // onClick={handleSearch}
          size="small"
          color="primary"
          style={{ marginLeft: 8 }}
        >
          搜索
        </Button>
      </div>

      {/* 图片轮播区域 */}
      <div style={{ background: "#fff" }}>
        <Swiper loop autoplay style={{}}>
          {(data.img || []).map((img, i) => (
            <Swiper.Item key={i}>
              <img
                src={img.url}
                onError={(e) => {
                  e.target.onerror = null;
                  e.target.src = FALLBACK_IMG;
                }}
                alt=""
                style={{
                  width: "100%",
                  height: "400px",
                  //   objectFit: "contain",
                  //   display: "block",
                  //   background: "#f2f2f2",
                }}
              />
            </Swiper.Item>
          ))}
        </Swiper>
      </div>

      {/* 商品信息卡片 */}
      <div style={{ padding: "12px", background: "#fff", marginTop: 10 }}>
        <h2 style={{ fontSize: 18, fontWeight: "bold", marginBottom: 6,display:'flex',justifyContent:'space-between' }}>
          名称：{data.title}
       <Button
  fill="none"
  onClick={shoucang}
  style={{ color: collect ? 'red' : '#888' }}
>
  {collect ? '❤️ 已收藏' : '🤍 收藏'}
</Button>
        </h2>
        <div
          style={{
            color: "#f53f3f",
            fontSize: 20,
            fontWeight: "bold",
            marginBottom: 10,
          }}
        >
          ¥ {data.price || "面议"}
        </div>
        <div style={{ color: "#666", fontSize: 14, lineHeight: 1.5 }}>
          {data.desc || "暂无描述"}
        </div>
      </div>

      {/* 补充信息 */}
      <div
        style={{
          marginTop: 10,
          padding: "12px",
          background: "#fff",
          fontSize: 13,
          color: "#666",
          lineHeight: 1.6,
        }}
      >
        <div>
          <strong>分类：</strong>
          {data.type || "未分类"}
        </div>
        <div>
          <strong>发布时间：</strong>
          {new Date(data.createdAt).toLocaleString()}
        </div>
        <div>
          <strong>联系方式：</strong>
          {data.contact || "未提供"}
        </div>
      </div>

      {/* 猜你喜欢 */}
      {guessList.length > 0 && (
        <div style={{ background: "#fff", marginTop: 10, padding: "12px" }}>
          <h3 style={{ fontSize: 16, marginBottom: 10 }}>猜你喜欢</h3>
          <div
            style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}
          >
            {guessList.map((item) => (
              <div
                key={item._id}
                onClick={() => navigate(`/detail/${item._id}`)}
                style={{
                  border: "1px solid #eee",
                  borderRadius: 8,
                  overflow: "hidden",
                  background: "#fafafa",
                }}
              >
                <img
                  src={item.img?.[0]?.url}
                  alt={item.title}
                  style={{ width: "100%", height: 100, objectFit: "cover" }}
                  onError={(e) => {
                    e.target.onerror = null;
                    e.target.src = FALLBACK_IMG;
                  }}
                />
                <div style={{ padding: "5px 8px" }}>
                  <div
                    style={{
                      fontSize: 14,
                      whiteSpace: "nowrap",
                      overflow: "hidden",
                      textOverflow: "ellipsis",
                    }}
                  >
                    {item.title}
                  </div>
                  <div style={{ color: "#f53f3f", fontWeight: "bold" }}>
                    ¥ {item.price || "面议"}
                  </div>
                </div>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* 底部按钮 */}
      <div
        style={{
          position: "fixed",
          bottom: 0,
          left: 0,
          right: 0,
          background: "#fff",
          borderTop: "1px solid #eee",
          padding: "10px 12px",
          display: "flex",
          gap: 12,
        }}
      >
        <Button block color="primary">
          联系卖家
        </Button>
        <Button block color="warning" disabled={!localStorage.getItem('user')} onClick={()=>{
          axios.post('http://127.0.0.1:3000/cartadd',{user_id:JSON.parse(localStorage.getItem('user')),cart_id:id}).then(res=>{
            if(res.data.code===200){
              Toast.show({icon:'success',content:'已加入购物车'})
            }
          })
        }}>
          {localStorage.getItem('user')?"我想要":'请去登录'}
        </Button>
      </div>
    </div>
  );
}
